package com.anji.plus.gaea.utils;

import com.anji.plus.gaea.annotation.GaeaMask;
import com.anji.plus.gaea.annotation.resolver.mask.MaskEnum;

/**
 * 数据脱敏
 * @author lr
 * @since 2021-02-04
 */
public class GaeaMaskUtils {

    /**
     * 默认的脱敏规则
     */
    public static final String defaultPattern = "(\\w{1})\\w+(\\w{1})";

    /**
     * 数据脱敏
     * @param source
     * @param reg 正则表达式
     * @param replacement 替换表达式
     * @return
     */
    public static String mask(String source, String reg, String replacement) {
        return source.replaceAll(reg, replacement);
    }


    public static String getMaskValue(String value, MaskEnum type, GaeaMask gaeaMask) {
        //当不是通用类型时，忽略GaeaMask注解其他字段
        String result = "";
        if (type != MaskEnum.COMMON) {
            result = GaeaMaskUtils.mask(value, type.getPattern(), type.getReplacement());
        } else {
            String pattern = type.getPattern();
            int left = gaeaMask.left();
            int right = gaeaMask.right();
            //当设置的左右长度大于对应值的长度时，直接采用默认脱敏规则
            String patternFormat;
            if (left + right >= value.length()) {
                patternFormat = GaeaMaskUtils.defaultPattern;
            } else {
                patternFormat = String.format(pattern, gaeaMask.left(), gaeaMask.right());
            }
            result = GaeaMaskUtils.mask(value, patternFormat, type.getReplacement());
        }
        return result;
    }
}
